﻿using LPBToolsLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using static WxWorkPullMsg.FWxWorkPullMsgDemo;

namespace WxWorkPullMsg
{
    public class WxWork_GetAccessToken
    {
        public string s企业ID { get; private set; }
        public string s应用Secret { get; private set; }
        private const string url_GetAccessToken_Mask = @"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
        private readonly HttpClient _httpClient=new HttpClient();
        private tAccessTokenRun tATokenRun { get; set; } = null;
        public string AccessToken
        {
            get
            {
                if ((tATokenRun != null) && (tATokenRun.expires_in > 30))
                    return tATokenRun.access_token;
                return "";
            }
        }

        public WxWork_GetAccessToken(string 企业ID,string 应用Secret)
        {
            s企业ID = 企业ID;
            s应用Secret = 应用Secret;
            Thread thd=new Thread(thdMainRun);
            thdRunActive = true;
            thd.Start();
        }

        public void closeAll()
        {
            thdRunActive = false;
            tATokenRun = null;
        }

        bool onGetAccessToken = false;

        private int GetAccessToken()
        {
            var requestUrl = string.Format(url_GetAccessToken_Mask, s企业ID, s应用Secret);
            string result = "";
            onGetAccessToken = true;
            try
            {
                int iResult = HttpReqTools.GetRequest(requestUrl, null, out result);
                if (iResult != 200)
                {
                    throw new Exception($"获取 AccessToken 失败，HTTP状态码: {iResult}");
                }
                var tokenResult = JsonSerializer.Deserialize<AccessTokenResult>(result);
                if (tokenResult == null || tokenResult.errcode != 0)
                {
                    throw new Exception($"获取 AccessToken 失败，错误码: {tokenResult?.errcode}，错误信息: {tokenResult?.errmsg}");
                }
                // 缓存新的 AccessToken
                tATokenRun = new tAccessTokenRun(tokenResult.access_token, tokenResult.expires_in-30);
                return iResult;
            }
            finally
            {
                onGetAccessToken = false;
            }
        }

        private class AccessTokenResult
        {
            public int errcode { get; set; }
            public string errmsg { get; set; }
            public string access_token { get; set; }
            public int expires_in { get; set; }
        }

        public class tAccessTokenRun
        {
            private DateTime tCreateDT = DateTime.Now;

            public string access_token { get; private set; }
            public int expires_in { get { return (int)(iExpiresStar - (DateTime.Now - tCreateDT).TotalSeconds); } }
            private int iExpiresStar = 7000;
            public tAccessTokenRun(string accesstoken, int expiresStar)
            {
                access_token = accesstoken;
                iExpiresStar = expiresStar;
            }
        }

        private bool thdRunActive = false;
        private void thdMainRun()
        {
            while (thdRunActive)
            {
                try
                {
                    if ((tATokenRun==null)||((tATokenRun!=null)&&(tATokenRun.expires_in<30)))
                        if (!onGetAccessToken)
                            GetAccessToken();
                }
                finally
                {
                    Thread.Sleep(1);
                }
            }
        }
    }
}
